package com.wrupple.muba.common.client;

import com.google.gwt.user.client.ui.Widget;

public class MubaUtilities {
	
	
	public static int getNonZeroParentWidth(Widget w){
		Widget parent = w.getParent();
		int width = parent.getOffsetWidth();
		
		while(width == 0) {
			width = parent.getOffsetWidth();
			parent = parent.getParent();
		}
		
		return width;
	}
	
	
	public static int getNonZeroParentHeight(Widget w){
		Widget parent = w.getParent();
		int width = parent.getOffsetHeight();
		
		while(width == 0) {
			width = parent.getOffsetHeight();
			parent = parent.getParent();
		}
		
		return width;
	}

	/**
	 * Generates an array of visually distinct color hexes
	 * 
	 * @param size
	 * @param r
	 * @param g
	 * @param b
	 * @return
	 */
	public static String[] generateColorArray(int size, int r, int g, int b) {
		String[] regreso = new String[size];
		int step = 1530 / size;
		for (int i = 0; i < regreso.length; i++) {
			regreso[i] = getColorFromSpace(i * step, r, g, b);
		}
		return regreso;
	}

	/**
	 * @param b
	 * @param g
	 * @param r
	 * @param colorUnit
	 *            a number ranging from 0 to 1530 (which is the RGB color space)
	 * @return
	 */
	public static String getColorFromSpace(int colorPoint, int r, int g, int b) {
		int[] comps = getColorComponentsFromSpace(colorPoint, r, g, b);
		return "#" + toColorHex(comps[0]) + toColorHex(comps[1]) + toColorHex(comps[2]);
	}

	/**
	 * @param b
	 * @param g
	 * @param r
	 * @param colorUnit
	 *            a number ranging from 0 to 1530 (which is the RGB color space)
	 * @return
	 */
	public static int[] getColorComponentsFromSpace(int colorPoint, int r, int g, int b) {
		int rr = calculateBlue(colorPoint + 510, r);
		int gg = calculateBlue(colorPoint + 1020, g);
		int bb = calculateBlue(colorPoint, b);
		return new int[] { rr, gg, bb };
	}

	private static int calculateBlue(int point, int plusvalue) {
		int plot = point % 1530;
		if (plot <= 510) {
		} else {
			plot = 1020 - plot;
		}
		return rgbFloorTop(rgbFloorTop(plot) + plusvalue);
	}

	private static int rgbFloorTop(int point) {
		if (point > 255) {
			return 255;
		}
		if (point < 0) {
			return 0;
		}
		return point;
	}

	private static String toColorHex(int component) {
		String regreso = Integer.toHexString(component);
		if (component <= 15) {
			regreso = "0" + regreso;
		}
		return regreso;
	}
}
